package com.research.web.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.research.web.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.research.web.utils.DruidUtils.closeConnection;
import static com.research.web.utils.UserBeanUtils.getUserEntity;
import static com.research.web.utils.UserServiceUtils.saveOrUpdateBatch;

public class UserSynchronizeUtils {
    private static final String QUERY_USER = "select * from sys_user";



    public static Boolean synchronizeAllUserInfo(List<DruidDataSource> dataSourceList) throws Exception {
        /***  查询所有应用系统的数据全集（不去重） ***/
        Map<String, List<UserEntity>> map = new HashMap<>();
        List<UserEntity> allList = new ArrayList<>();
        for (DruidDataSource druidDataSource : dataSourceList) {
            String name = druidDataSource.getName();

            DruidPooledConnection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;

            try {
                connection = druidDataSource.getConnection();
                if (connection == null) {
                    throw new RuntimeException("数据库连接失败:" + name);
                }
                preparedStatement = connection.prepareStatement(QUERY_USER);
                resultSet = preparedStatement.executeQuery();
                List<UserEntity> UserEntityList = getUserEntity(resultSet);
                map.put(name, UserEntityList);
                allList.addAll(UserEntityList);
            } catch (Exception e) {
                throw new RuntimeException("数据查询失败:" + e);
            } finally {
                closeConnection(connection, preparedStatement, resultSet);
            }
        }

        /*** 对应用系统进行用户数据同步 ***/
        // 获取各系统需要同步的用户集合
        Map<String, List<UserEntity>> serviceMap = getServiceUserEntities(map, allList);
        // 数据同步
        for (DruidDataSource druidDataSource : dataSourceList) {
            String name = druidDataSource.getName();
            List<UserEntity> userEntities = serviceMap.get(name);
            if (ObjectUtils.isEmpty(userEntities)) {
                continue;
            }
            // 待同步的用户集合不为空，此时进行数据同步
            saveOrUpdateBatch(druidDataSource, userEntities);
        }
        return true;
    }

    /*** 获取各系统需要同步的用户集合 ***/
    public static Map<String, List<UserEntity>> getServiceUserEntities(Map<String, List<UserEntity>> serviceMap, List<UserEntity> unionList) {
        /**** 获取所有应用系统的用户去重集合: 对重复的用户信息，以用户最新修改时间的记录为准 *****/
        Map<Integer, UserEntity> tempMap = new HashMap();
        List<UserEntity> setList = new ArrayList<>();
        for (UserEntity userEntity : unionList) {
            Integer id = userEntity.getId();
            UserEntity u = tempMap.get(id);
            if (ObjectUtils.isEmpty(u)) {
                tempMap.put(id, userEntity);
                setList.add(userEntity);
            } else {
                LocalDateTime updateTime = u.getUpdateTime();
                LocalDateTime updateTime1 = userEntity.getUpdateTime();
                if (updateTime1.isAfter(updateTime)) {
                    tempMap.put(id, userEntity);
                    setList.remove(u);
                    setList.add(userEntity);
                }
            }
        }
        /**** 组织不同应用系统需要同步的数据信息,key为应用系统id ****/
        Map<String, List<UserEntity>> result = new HashMap<>();
        Set<String> strings = serviceMap.keySet();
        for (String key : strings) {
            List<UserEntity> tempList = new ArrayList<>(setList);
            List<UserEntity> userEntities = serviceMap.get(key);
            tempList.removeAll(userEntities);
            result.put(key, tempList);
        }
        return result;
    }

    /*** 应用系统单条用户数据同步 ***/
    public static boolean serviceSynchronize(List<DruidDataSource> dataSourceList, Map<String, Object> userMap) throws Exception {
        String serviceId = userMap.get("serviceId").toString();
        List<DruidDataSource> druidDataSources = dataSourceList.parallelStream().filter(e -> serviceId.equals(e.getName())).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(druidDataSources)) {
            throw new RuntimeException("未发现对应的业务系统");
        } else {
            dataSourceList.removeAll(druidDataSources);
            List<UserEntity> userEntities = getUserEntity(userMap);
            for (DruidDataSource druidDataSource : dataSourceList) {
                saveOrUpdateBatch(druidDataSource, userEntities);
            }
            return true;
        }
    }

    public static boolean serviceSynchronize(List<DruidDataSource> dataSourceList, UserEntity userEntity, String serviceId) throws Exception {
        List<DruidDataSource> druidDataSources = dataSourceList.parallelStream().filter(e -> serviceId.equals(e.getName())).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(druidDataSources)) {
            throw new RuntimeException("未发现对应的业务系统");
        } else {
            List<UserEntity> userEntities = new ArrayList<>();
            userEntities.add(userEntity);

            List<DruidDataSource> tempList = new ArrayList<>(dataSourceList);
            tempList.removeAll(druidDataSources);
            for (DruidDataSource druidDataSource : tempList) {
                saveOrUpdateBatch(druidDataSource, userEntities);
            }
            return true;
        }
    }
}
